#!/usr/bin/python
########################################################################
# ddup.py - Digital Dailies uploader script for modo2.  Collects values
#	from the user and from modo itself, and uses that to build a command
#	line for launching wickddup.py.
#
# Created 2006.09.22 by Warren Young
#
# Copyright (c) 2006 by Pixel Corps.  This program may be used under
# the terms of the X11 license, a copy of which should have accompanied
# this program, in the LICENSE file.
########################################################################

import lx

import os


class Scene(object):
	'''Wrapper around modo's sceneservice. Currently supports only
	retrieving the attributes of the scene itself, not of its contents.'''

	def __init__(self):
		pass

	def changed(self):
		return lx.eval("query sceneservice scene.changed ? current")

	def count(self):
		return lx.eval("query sceneservice scene.N ?")

	def file(self):
		return lx.eval("query sceneservice scene.file ? current")

	def format(self):
		return lx.eval("query sceneservice scene.format ? current")

	def index(self):
		return lx.eval("query sceneservice scene.index ? current")

	def name(self):
		return lx.eval("query sceneservice scene.name ? current")
		


class UserValue(object):
	'''Wrapper around a modo "user value" object. Makes using them more
	pythonic: removes the need to use the modo scripting langauge
	directly.  Module lx does nothing to hide that by itself.'''

	def __init__(self, name, type = 'string', *values):
		self.name = name
		
		uvDef = "query scriptsysservice userValue.isdefined ? " + name
		if not lx.eval(uvDef):
			lx.eval("!!user.defNew %s %s" % (name, type))
			if len(values):
				self.value = values


	def setLabel(self):
		lx.eval('!!user.def %s username "%s"' % (self.name, value))

	label = property(None, setLabel, None, None)


	def getValue(self):
		return lx.eval( "user.value %s ?" % self.name)

	def setValue(self, value):
		if isinstance(value, list) or isinstance(value, tuple):
			lx.eval("!!user.def %s list %s" % (self.name, ';'.join(value)))
		else:
			lx.eval( "!!user.value %s %s", (self.name, value))

	value = property(getValue, setValue, None, None)


def getTempPath():
	'''Figure out the best 'temp' directory to use'''

	if 'TEMP' in os.environ:
		return os.environ['TEMP']
	else:
		if os.name == 'mac' or os.name == 'posix':
			return '/tmp'
		else:
			return 'C:/'


## Start of the script proper

# Grab the user's form entries
userName = UserValue('ddupUserName')
hostName = UserValue('ddupHostName')
remoteDir = UserValue('ddupRemoteDir')
remoteDirVar = UserValue('ddupRemoteDirVar')
modelOnly = UserValue('ddupModelOnly', 'boolean')
projectName = UserValue('ddupProjectName')
sceneName = UserValue('ddupSceneName')
elementName = UserValue('ddupElementName')
artistName = UserValue('ddupArtistName')
notes = UserValue('ddupNotes')

# Get info about the scene file
scene = Scene()
(root, ext) = os.path.splitext(os.path.basename(scene.file()))
ddofile = '%s%s%s.ddo' % (getTempPath(), os.path.sep, root)

# Create the DDO file to pass the user's entries from the plugin to the
# ddup program.
f = open(ddofile, 'w')
f.write('opts = [\n')
f.write("\t('-m', ''),\n")
f.write("\t('-s', ''),\n")
f.write("\t('-u', '%s'),\n" % userName.value)
f.write("\t('-h', '%s'),\n" % hostName.value)
f.write("\t('-r', '%s'),\n" % remoteDir.value)
f.write("\t('-R', '%s'),\n" % remoteDirVar.value)
f.write("\t('-J', '%s'),\n" % projectName.value)
f.write("\t('-S', '%s'),\n" % sceneName.value)
f.write("\t('-E', '%s'),\n" % elementName.value)
f.write("\t('-U', '%s'),\n" % artistName.value)
f.write("\t('-N', '%s'),\n" % notes.value)
f.write(']\n')
f.write('args = [\n')
f.write("\t'%s',\n" % scene.file())
f.write(']\n')
f.close()

# Launch the file: use creator code and LaunchServices on OS X, and
# the ShellExecute() API on Win32.  This'll break down on Linux, for
# whatever that's worth.
if os.name == 'mac' or os.name == 'posix':
	import Carbon.File
	fss = Carbon.File.FSSpec(ddofile)
	fi = fss.FSpGetFInfo()
	fi.Creator = 'PXC1'
	fi.Type = 'DDUP'
	fss.FSpSetFInfo(fi)

	if os.sys.hexversion >= 0x02040000:
		import Carbon.Launch				# the "right" way
		Carbon.Launch.LSOpenFSRef(Carbon.File.FSRef(ddofile))
	else:
		os.system('open "%s"' % ddofile)	# fall back on open(1)
else:
	# Not tested, but should work
	import win32api
	win32api.ShellExecute(0, 'open', ddofile, None, '.', 1)

